<template>
  <uni-popup ref="popupRef" type="bottom">
    <view class="authorize">
      <view class="text">授权后可查看更多内容</view>
      <button class="auth" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">一键授权</button>
      <button class="cancel" @click="closeAuthroizePopup">取消</button>
    </view>
  </uni-popup>
</template>

<script>
  import {
    mapActions
  } from 'vuex'
  import {
    getOpenIdApi
  } from '@/api/login.js'
  import host from '@/utils/ipConfig.js'
  export default {
    methods: {
      ...mapActions(['setBusinessInfo', 'setUserCollectInfo']),
      checkAuthorize() {
        const _this = this
        return new Promise((resolve, reject) => {
          const openid = uni.getStorageSync('openid')
          if (openid) {
            resolve()
          } else {
            console.log('执行授权')
            _this.openAuthroizePopup()
            reject()
          }
        })
      },
      openAuthroizePopup() {
        this.$refs.popupRef.open('bottom')
      },
      closeAuthroizePopup() {
        this.$refs.popupRef.close('bottom')
      },
      getPhoneNumber(e) {
        if (e.detail.errMsg === 'getPhoneNumber:ok') {
          const _this = this
          uni.login({
            provider: 'weixin',
            success: async (e) => {
              const {
                code,
                data
              } = await getOpenIdApi({
                appid: host.appId,
                code: e.code,
                grantType: 'authorization_code'
              })
              if (code === '000000') {
                uni.setStorageSync('openid', data.openid)
                _this.setBusinessInfo()
                _this.setUserCollectInfo()
                uni.showToast({
                  title: '授权成功'
                })
                _this.$emit('authSuccess')
                _this.$refs.popupRef.close('bottom')
              }
            }
          })
        } else {
          uni.showToast({
            icon: 'none',
            title: '您拒绝了授权'
          })
        }
      },
    }
  }
</script>

<style lang="scss" scoped>
  .authorize {
    height: 50vh;
    background-color: #333;
    color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 80rpx 40rpx 40rpx;
    box-sizing: border-box;

    .text {
      font-size: 32rpx;
      color: #999;
      background-color: transparent;
    }

    button {
      width: 100%;
      height: 80rpx;
      font-size: 32rpx;
      line-height: 80rpx;
      background-color: rgb(92, 189, 112);
      color: #fff;
    }

    .auth {
      margin-top: auto;
    }

    .cancel {
      margin: 30rpx;
      background-color: #fff;
      color: rgb(92, 189, 112);
    }
  }
</style>
